package com.smartcruise.util.network;

import android.os.Handler;
import android.util.Log;

import com.alibaba.sdk.android.oss.ClientException;
import com.alibaba.sdk.android.oss.ServiceException;
import com.alibaba.sdk.android.oss.callback.OSSCompletedCallback;
import com.alibaba.sdk.android.oss.callback.OSSProgressCallback;
import com.alibaba.sdk.android.oss.internal.OSSAsyncTask;
import com.alibaba.sdk.android.oss.model.PutObjectRequest;
import com.alibaba.sdk.android.oss.model.PutObjectResult;
import com.smartcruise.util.network.callBack.UploadFileCallBack;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by FengChaoQun
 * on 2018/2/8 0008
 * 上传文件到OSS
 */

public class FileUpload {

    private Map<String, String> fileList = new HashMap<>();
    private List<String> keyList = new ArrayList<>();
    private UploadFileCallBack uploadFileCallBack;
    private long totalLength;
    private long currentLength;
    private OSSAsyncTask ossAsyncTask;
    private int currentPosition;
    private Handler handler = new Handler();

    public FileUpload(Map<String, String> fileList) {
        this.fileList = fileList;
    }

    public FileUpload(Map<String, String> fileList, UploadFileCallBack uploadFileCallBack) {
        this.fileList = fileList;
        this.uploadFileCallBack = uploadFileCallBack;
    }

    /**
     * description:开始上传
     */

    public void start() {
        if (uploadFileCallBack != null) {
            uploadFileCallBack.onStart();
        }
        if (fileList == null || fileList.isEmpty()) {
            if (uploadFileCallBack != null) {
                uploadFileCallBack.onFailure(null, new ClientException("上传的数据不存在"), null);
            }
        } else {
            for (Map.Entry<String, String> stringStringEntry : fileList.entrySet()) {
                keyList.add(stringStringEntry.getKey());
                File file = new File(stringStringEntry.getValue());
                totalLength += file.length();
            }
            Log.d("FileUpload", "totalLength:" + totalLength);
            uploadFiles();
        }
    }

    /**
     * description:上传单个文件
     */

    private OSSAsyncTask upLoadFile(String filePath, String key, final UploadFileCallBack callBack) {
        PutObjectRequest put = new PutObjectRequest(OssManager.getBucket(), key, filePath);
        // 异步上传时可以设置进度回调
        put.setProgressCallback(new OSSProgressCallback<PutObjectRequest>() {
            @Override
            public void onProgress(PutObjectRequest request, long currentSize, long totalSize) {
                if (callBack != null) {
                    callBack.onProgress(request, currentSize, totalSize);
                }
            }
        });
        if (callBack != null) {
            callBack.onStart();
        }
        return OssManager.getOss().asyncPutObject(put, new OSSCompletedCallback<PutObjectRequest, PutObjectResult>() {
            @Override
            public void onSuccess(PutObjectRequest request, PutObjectResult result) {
                if (callBack != null) {
                    callBack.onSuccess(request, result);
                }
            }

            @Override
            public void onFailure(PutObjectRequest request, ClientException clientExcepion, ServiceException serviceException) {
                if (callBack != null) {
                    callBack.onFailure(request, clientExcepion, serviceException);
                }
            }
        });
    }

    /**
     * description:上传多个文件
     */

    private void uploadFiles() {
        String key = keyList.get(currentPosition);
        ossAsyncTask = upLoadFile(fileList.get(key), key, new UploadFileCallBack() {

            private long lastCurrentSize = 0;//最近一次已上传的文件大小

            @Override
            public void onStart() {

            }

            @Override
            public void onProgress(final PutObjectRequest request, final long currentSize, long totalSize) {
                handler.post(new Runnable() {
                    @Override
                    public void run() {
                        currentLength += (currentSize - lastCurrentSize);
                        if (uploadFileCallBack != null) {
                            uploadFileCallBack.onProgress(request, currentLength, totalLength);
                        }
                        lastCurrentSize = currentSize;
                    }
                });
            }

            @Override
            public void onSuccess(final PutObjectRequest request, final PutObjectResult result) {
                handler.post(new Runnable() {
                    @Override
                    public void run() {
                        if (currentPosition == keyList.size() - 1) {//上传完毕
                            if (uploadFileCallBack != null) {
                                uploadFileCallBack.onSuccess(request, result);
                            }
                        } else {
                            currentPosition++;
                            uploadFiles();
                        }
                    }
                });
            }

            @Override
            public void onFailure(final PutObjectRequest request, final ClientException clientExcepion, final ServiceException serviceException) {
                handler.post(new Runnable() {
                    @Override
                    public void run() {
                        if (uploadFileCallBack != null) {
                            uploadFileCallBack.onFailure(request, clientExcepion, serviceException);
                        }
                    }
                });
            }
        });
    }

    /**
     * description:取消上传
     */

    private void cancel() {
        uploadFileCallBack = null;
        ossAsyncTask.cancel();
    }

    public long getTotalLength() {
        return totalLength;
    }

    public long getCurrentLength() {
        return currentLength;
    }

    public int getCurrentPosition() {
        return currentPosition;
    }

    public void setUploadFileCallBack(UploadFileCallBack uploadFileCallBack) {
        this.uploadFileCallBack = uploadFileCallBack;
    }

}
